package cn.stronglink.esm27.collection.iot.devices.esm27.request.handle;

import java.io.IOException;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.alibaba.fastjson.JSONObject;

import cn.stronglink.esm27.collection.core.message.IMessageHandle;
import cn.stronglink.esm27.collection.core.util.ByteUtil;
import cn.stronglink.esm27.collection.core.util.ContextUtils;
import cn.stronglink.esm27.collection.iot.devices.esm27.ESM27Server;
import cn.stronglink.esm27.collection.iot.devices.esm27.message.MQMessageOfESM27;
import cn.stronglink.esm27.collection.iot.devices.esm27.request.entity.ESM27RequestMessageFactory;
import cn.stronglink.esm27.collection.iot.devices.esm27.request.entity.SensorBasePropertyEntity;
import io.netty.channel.ChannelHandlerContext;

/**
 * 获取传感器配置的处理
 * @author yuzhantao
 *
 */
public class GetSensorOptionHandle implements IMessageHandle<MQMessageOfESM27, Object> {
	private static Logger logger = LogManager.getLogger(GetSensorOptionHandle.class.getName());
	private final static String ACTION_CODE = "GetSensorOption"; // MQ中判断消息类型的标识符
	private ESM27Server esm27Server=(ESM27Server) ContextUtils.getBean("esm27Server"); // esm27服务器
	
	@Override
	public boolean isHandle(MQMessageOfESM27 t) {
		if (t.getActioncode().equals(ACTION_CODE)) {
			return true;
		} else {
			return false;
		}
	}

	@Override
	public Object handle(ChannelHandlerContext ctx, MQMessageOfESM27 t) {
		try {
			SensorBasePropertyEntity sensorProperty = ((JSONObject)t.getAwsPostdata()).toJavaObject(SensorBasePropertyEntity.class);
			byte[] sendDatas = ESM27RequestMessageFactory.createMessage(
					sensorProperty.getDeviceAddress(),
					(byte)0x04,
					new byte[] {((Integer)sensorProperty.getSensorChannelNumber()).byteValue()});
			esm27Server.send(sendDatas);
			logger.info("发送消息到ESM27:{}", ByteUtil.byteArrToHexString(sendDatas, true));
		} catch (IOException e) {
			logger.error(e);
		}
		return null;
	}

}
